package com.chb.sso.aspect;

import com.chb.sso.feign.LogInfoFeign;
import com.chb.sso.feign.UserFeign;
import com.chb.system.annotation.LogInfoAnnotation;
import com.chb.system.service.LoginInfoService;
import com.chb.system.service.UserService;
import com.hos.entity.sys.LoginInfo;
import com.hos.entity.sys.User;
import com.hos.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author ：张家琪
 * @date ：Created in 2023/12/26 15:24
 * @description：
 * @modified By：
 * @version:
 */
@Component
@Aspect
@Slf4j
public class LogInfoAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogInfoFeign loginInfoService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private UserFeign userService;

    @Pointcut("@annotation(com.chb.system.annotation.OperLogAnnotation)")
    private void pointcut() {
    }

    @Around("pointcut()")
    public Object my(ProceedingJoinPoint joinPoint) {
        // 添加日志--日志对象
        LoginInfo loginInfo = new LoginInfo();
        User user = getUserByToken();
        // 获取切面切入的方法对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogInfoAnnotation annotation = method.getAnnotation(LogInfoAnnotation.class);
        // 用户姓名
        loginInfo.setUserName(user.getUserName());
        //  登录账号（手机号码）
        loginInfo.setLoginAccount(user.getPhone());
        //  IP(192......)
        loginInfo.setIpAddr(request.getRemoteAddr());
        //  登录状态
        loginInfo.setLoginStatus(annotation.login_status());
        //  用户类型
        loginInfo.setLoginType(annotation.login_type());
        //   登录时间
        loginInfo.setLoginTime(new Date());
        try {
            Object result = joinPoint.proceed();
            return result;
        } catch (Throwable e) {
            log.error("日志Aop出现错误" + e.getMessage());
            throw new RuntimeException(e);
        } finally {
            this.loginInfoService.addLogInfo(loginInfo);
        }
    }

    /**
     * @return com.hos.entity.sys.User
     * @create by: 陈海彬
     * @description: 获取请求用户的信息
     * @create time: 2023/12/12 10:39
     */
    private User getUserByToken() {
        String token = WebUtil.getToken();
        String phone = redisTemplate.opsForValue().get("user:" + token);
        return userService.selectUserByPhone(phone);
    }
}